<template>
  <div class="login-container">
    <div class="login_box">
      <!-- 头像区域 -->
      <div class="head">
        <img src="./../assets/logo.png" alt="">
      </div>
      <!-- 表单区域 -->
      <el-form :model="loginForm" ref="loginFormRef" :rules="loginFormRules" class="login_form">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <!-- 添加前置小图标 -->
          <el-input v-model="loginForm.username" prefix-icon="el-icon-user-solid"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" show-password></el-input>
        </el-form-item>
        <!-- 登录注册 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="login()">登录</el-button>
          <el-button type="info" @click="resetLoginForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表单数据双向绑定
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 表单数据验证
      loginFormRules: {
        // required必选项
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 表单信息重置
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields();
    },
    login() {
      // 表单提交验证validate
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("login", this.loginForm)
        if (res.meta.status !== 200) return this.$message.error("登录失败")
        this.$message.success("登录成功");
        // 将登录成功的后台返回的token存储在sessionStorage
        // 项目中的其它的API接口必须在登录之后访问
        // token只在网页打开期间邮箱，所以保存至sessionStorage中
        window.sessionStorage.setItem("token", res.data.token);
        // 通过编程式导航跳转到后台首页
        this.$router.push("/home");
      })
    }
  }

}
</script>

<style lang="less" scoped>
.login-container {
  background-color: #045388;
  height: 100%;
}

.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 5%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.head {
  width: 130px;
  height: 130px;
  border: 3px solid #fff;
  background-color: #fff;
  box-shadow: 0 0 10px rgb(210, 208, 208);
  border-radius: 50%;
  overflow: hidden;
  position: absolute;
  left: 50%;
  top: 0;
  transform: translate(-50%, -50%);

  img {
    width: 100%;
    height: 100%;
  }
}

.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;

  .btns {
    display: flex;
    justify-content: end;
  }
}
</style>